﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Frogism.Core;
using System.Collections.ObjectModel;

namespace Frogism.Data {
  public class BookLoader : LoaderUpdateBase<Book, IBook> {
    private AuthorLoader _AuthorLoader;
    protected AuthorLoader AuthorLoader {
      get {
        if(_AuthorLoader == null) {
          _AuthorLoader = new AuthorLoader();
        }
        return _AuthorLoader;
      }
    }
    private ReadLoader _ReadLoader;
    protected ReadLoader ReadLoader {
      get {
        if(_ReadLoader == null) {
          _ReadLoader = new ReadLoader();
        }
        return _ReadLoader;
      }
    }
    protected override IBook GetEmptyObject() {
      return new Book();
    }
    protected override void FillObject(IBook book,FriendlyReader reader) {
      book.Title = reader.String("Title");
      book.Author = AuthorLoader.GetById(reader.Int("AuthorId"));
      book.LastPageNumber = reader.Int("TotalPages");
      book.IsFinished = reader.Bool("IsFinished");
      book.GoalYear = reader.Int("Year");
      book.IsPrivate = reader.Bool("IsPrivate");
      if (!reader.IsNull("IndexLength")) book.IndexLength = reader.Int("IndexLength");
      if (!reader.IsNull("Factor")) book.Factor = reader.Double("Factor");

      FillReads(book);
    }
    protected override string ProcNameGetAll {
      get { return "BookGetAll"; }
    }

    protected override string ProcNameGetById {
      get { return "BookGetById"; }
    }
    private void FillReads(IBook book) {
      ((Book)book).SetReads(ReadLoader.ByBookId(book.Id));
    }

    protected override void FillParameters(System.Data.SqlClient.SqlCommand cmd, IBook book) {
      AddStringParam(cmd, "Title", book.Title);
      AddIntParam(cmd, "AuthorId", book.Author.Id);

      AddIntParam(cmd, "LastPageNumber", book.LastPageNumber);
      AddBoolParam(cmd, "IsFinished", book.IsFinished);
      AddBoolParam(cmd, "IsPrivate", book.IsPrivate);
      AddIntParam(cmd, "Year", book.GoalYear);

     
        AddIntParam(cmd, "IndexLength", book.IndexLength);
        AddDoubleParam(cmd, "Factor", book.Factor);
      

    }

    protected override string ProcNameSave {
      get { return "BookUpdate"; }
    }

    protected override string ProcNameCreate {
      get { return "BookInsert"; }
    }

    protected override string ProcNameDelete {
      get { return "BookDelete"; }
    }
       
  }
}
